/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Server;

import java.net.Socket;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import Socket.*;

/**
 *
 * @author Rui Deyllot
 */
public class Proxy extends Thread {

    private Socket com;
    private Prado field;

    public Proxy(Socket com, Prado field) {
        this.com = com;
        this.field = field;
    }

    public void run() {
        Message entrada = null;
        Response saida = null;
        ObjectOutputStream objOut = null;
        //receber objecto do socket e fazer cast para message
        try {
            ObjectInputStream objIn = new ObjectInputStream(com.getInputStream());
            objOut = new ObjectOutputStream(com.getOutputStream());
            entrada = (Message)objIn.readObject();
        }
        catch(IOException ex) {
            System.exit(1);
        }
        catch(ClassNotFoundException ex) {
            System.exit(1);
        }

        switch(entrada.getTipo())
        {
            /* chamar método correspondente ao case.
             * se método tem valor de retorno construir saida.
             */
            case hasSeeds: saida = new Response(field.hasSeeds(entrada.getX(), entrada.getY())); break;
            case hasCarrot: saida = new Response(field.hasCarrot(entrada.getX(), entrada.getY())); break;
            case carrotEnergy: saida = new Response(field.carrotEnergy(entrada.getX(), entrada.getY())); break;
            case canJump: saida = new Response(field.canJump(entrada.getCoelhoID(), entrada.getX(), entrada.getY(), entrada.getNewX(), entrada.getNewY())); break;
            case canGerminate: saida = new Response(field.canGerminate(entrada.getCenouraID(), entrada.getX(), entrada.getY())); break;
            case hasPollen: saida = new Response(field.hasPollen(entrada.getX(), entrada.getY())); break;
            case plantSeed: field.plantSeed(entrada.getX(), entrada.getY()); break;
            case informCoelho: field.informCoelho(entrada.getCoelhoID(), entrada.getRabbitState(), entrada.getX(), entrada.getY()); break;
            case informCenoura: field.informCenoura(entrada.getCenouraID(), entrada.getEnergy(), entrada.getCarrotState(), entrada.getX(), entrada.getY()); break;
            case getEndFlag: saida = new Response(field.getEndFlag());
        }

        //fazer cast de Response para objecto e enviar para o socket
        try {
            objOut.writeObject((Object)saida);
        }
        catch(IOException ex) {
            System.exit(1);
        }
    }
}
